import 'dart:core';

import 'package:boxes_flutter/flutter/slc/adapter/page_model.dart';
import 'package:boxes_flutter/flutter/slc/code/observable_field.dart';

/// @author: slc
///  刷新状态
enum LoadMoreStatus {
  /// 正在刷新
  refreshing,

  ///刷新完成
  refreshCompleted,

  ///刷新完成
  loadMoreCompleted,

  ///没有更多
  noMore,

  ///刷新失败
  failed
}
/// 用于处理加载更多逻辑的格式化类
///
/// [T] 列表项的数据类型
class LoadMoreFormat<T> {
  static const DEF_OFFICE = 1;
  static const DEF_SIZE = 15;
  int _baseOffset = DEF_OFFICE;
  int _offset = DEF_OFFICE;
  int _size = 15;

  int get baseOffset => _baseOffset;
  int get offset => _offset;
  int get size => _size;

  final ObservableField<LoadMoreStatus> refreshStatusOf = ObservableField();

  /// 构造函数，初始化偏移量和每页数量
  ///
  /// [offset] 初始偏移量，默认为 [DEF_OFFICE]
  /// [size] 每页数量，默认为 [DEF_SIZE]
  LoadMoreFormat({int offset = DEF_OFFICE, int size = DEF_SIZE}) {
    this._baseOffset = offset;
    this._offset = this._baseOffset;
    this._size = size;
  }

  /// 根据 [PageModel] 对象格式化目标列表
  ///
  /// [targetList] 要更新的目标列表
  /// [pageModel] 包含分页信息的 [PageModel] 对象
  void formatByPageModel(List<T> targetList, PageModel<T> pageModel) {
    formatSimple(
        targetList, pageModel.getListNoNull(), pageModel.isLastPageSafe());
  }

  /// 简单格式化目标列表
  ///
  /// [targetList] 要更新的目标列表
  /// [sourceList] 源数据列表
  /// [isLastPage] 是否为最后一页
  void formatSimple(List<T> targetList, List<T> sourceList, bool isLastPage) {
    if (offsetEqualsBaseOffset()) {
      targetList.clear();
    }
    targetList.addAll(sourceList);
    if (offsetEqualsBaseOffset()) {
      refreshStatusOf.setValueForcedNotify(LoadMoreStatus.refreshCompleted);
    }
    if (isLastPage) {
      refreshStatusOf.setValueForcedNotify(LoadMoreStatus.noMore);
    } else {
      refreshStatusOf.setValueForcedNotify(LoadMoreStatus.loadMoreCompleted);
    }
    if (targetList.isEmpty) {
      return;
    }
    _offset++;
  }

  /// 加载更多失败时调用，设置刷新状态为失败
  void loadMoreFail() {
    refreshStatusOf.setValueForcedNotify(LoadMoreStatus.failed);
  }

  /// 刷新数据
  ///
  /// [notificationUi] 是否通知 UI 刷新，默认为 false
  void refresh({bool notificationUi = false}) {
    _offset = baseOffset;
    if (notificationUi) {
      refreshStatusOf.setValueForcedNotify(LoadMoreStatus.refreshing);
    }
  }

  /// 判断偏移量是否等于基础偏移量
  ///
  /// 返回值为 true 表示偏移量等于基础偏移量，否则为 false
  bool offsetEqualsBaseOffset() {
    return baseOffset == offset;
  }

}
